package com.zm.admin.quartz;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

import com.zm.admin.context.BeanContext;
import com.zm.admin.zmeng.domain.ZmScheduleJob;
import com.zm.admin.zmeng.domain.ZmScheduleLog;
import com.zm.admin.zmeng.service.ZmScheduleLogService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.lang.reflect.Method;


/**
 * Quartz Job 执行逻辑
 * <p>
 * 通过 className 反射生成实例, 执行任务并记录日志
 *
 * @serial 2.0.0
 * @author 就眠儀式
 */
@Slf4j
public class QuartzExecute extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext context) {
        log.info("job类动了");
        Object o = context.getMergedJobDataMap().get(ZmScheduleJob.JOB_PARAM_KEY);
        ZmScheduleJob jobBean = (ZmScheduleJob) o;
        ZmScheduleLogService logService = BeanContext.getBean(ZmScheduleLogService.class);
        ZmScheduleLog logBean = new ZmScheduleLog();
        logBean.setId(IdWorker.getIdStr());
        logBean.setJobId(jobBean.getId());
        logBean.setBeanName(jobBean.getBeanName());
        logBean.setParams(jobBean.getParams());
        logBean.setCreateTime(DateUtil.date());
        long beginTime = System.currentTimeMillis();
        try {
            //拿到该类
            Object springBean = BeanContext.getBean(jobBean.getBeanName());
            Method method = springBean.getClass().getDeclaredMethod("run", String.class);
            //反射运行该job对应springbean中指定Params的方法
            method.invoke(springBean, jobBean.getParams());
            long executeTime = System.currentTimeMillis() - beginTime;
            logBean.setTimes((int) executeTime);
            logBean.setStatus("1");
            log.info("定时器 === >> " + jobBean.getJobName() + "执行成功,耗时 === >> " + executeTime);
        } catch (Exception e) {
            long executeTime = System.currentTimeMillis() - beginTime;
            logBean.setTimes((int) executeTime);
            logBean.setStatus("0");
            logBean.setException(e.getMessage());
            e.getCause();
        } finally {
            logService.save(logBean);
        }
    }
}
